package com.cloud.common.security.feign;

import cn.dev33.satoken.same.SaSameUtil;
import com.cloud.common.core.constant.CommonConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        //1、使用RequestContextHolder拿到刚进来的请求数据
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            //老请求
            HttpServletRequest request = requestAttributes.getRequest();
            if (request != null) {
                //2、同步请求头的数据
                //把老请求的cookie值放到新请求上来，进行一个同步
                String cookie = request.getHeader(CommonConstants.cookie);
                String token=request.getHeader(CommonConstants.token);
                String authorization=request.getHeader(CommonConstants.authorization);
                String traceId=request.getHeader(CommonConstants.traceId);

                template.header(CommonConstants.cookie, cookie);
                template.header(CommonConstants.token, token);
                template.header(CommonConstants.authorization, authorization);
                template.header(CommonConstants.traceId, traceId);
                template.header(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken());
            }
        }
    }
}
